package edu.cuit.avatar.parallel;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/18 10:16
 */
public class ParallelMax {
    public static void main(String[] args) {
        final int SIZE = 5000000;
        int[] list = new int[SIZE];
        for(var i = 0; i < list.length; i++)
            list[i] = i;

        long start = System.currentTimeMillis();
        System.out.println("最大值为：" + max(list));
        System.out.println("并行处理器数量:" + Runtime.getRuntime().availableProcessors());
        System.out.println("花费时间:" + (System.currentTimeMillis() - start) + "ms");
    }

    public static int max(int[] list){
        var pool = new ForkJoinPool();
        return pool.invoke(new MaxTask(list, 0, list.length));
    }

    private static class MaxTask extends RecursiveTask<Integer>{
        private static final int THRESHOLD = 500;
        private int[] list;
        private int low;
        private int high;

        public MaxTask(int[] list, int low, int high) {
            this.list = list;
            this.low = low;
            this.high = high;
        }

        @Override
        protected Integer compute() {
            if(high - low < THRESHOLD){
                int max = list[0];
                for(int i = low; i < high; i++) {
                    if(list[i] > max)
                        max = list[i];
                }
                return max;//自动装箱
            } else {
                int mid = (low + high) / 2;
                //分解成两个子任务，分别找到左边和右半边的最大元素
                RecursiveTask<Integer> left = new MaxTask(list, low, mid);
                RecursiveTask<Integer> right = new MaxTask(list, mid, high);

                //每个子任务又递归的分解成更多的子任务
                left.fork();
                right.fork();

                return Math.max(left.join(),right.join());
            }
        }
    }
}
